package com.yixuan.mt.common.local.objects;

import com.yixuan.mt.common.constant.ObjectsIndexConstant;

import java.io.*;

public class ObjectsIndex {

    public static void createObjectsIndexFile(String bucketName) throws IOException {
        File file = new File(ObjectsIndexConstant.OBJECTS_INDEX_PREFIX_PATH + bucketName + ObjectsIndexConstant.OBJECTS_INDEX_SUFFIX_PATH);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
    }

    public static void addIndex(String bucketName, int index) throws IOException {
        // 写入文件
        FileOutputStream fo = new FileOutputStream(ObjectsIndexConstant.OBJECTS_INDEX_PREFIX_PATH + bucketName + ObjectsIndexConstant.OBJECTS_INDEX_SUFFIX_PATH, true);
        DataOutputStream dos = new DataOutputStream(fo);
        try (fo; dos) {
            dos.writeInt(index);
        }
    }

    public static int getIndex(String bucketName, int i) throws IOException {
        // 读取文件
        File file = new File(ObjectsIndexConstant.OBJECTS_INDEX_PREFIX_PATH + bucketName + ObjectsIndexConstant.OBJECTS_INDEX_SUFFIX_PATH);
        FileInputStream fi = new FileInputStream(file);
        DataInputStream di = new DataInputStream(fi);
        try (fi; di) {
            di.skip((long) i * ObjectsIndexConstant.OBJECTS_INDEX_LENGTH);
            return di.readInt();
        }
    }
}
